import { View } from "@tarojs/components";
import { useState } from "react";
import { Tabs, ConfigProvider, List, Loading } from "@taroify/core";
import MatchCard from "@/components/MatchCard";
import { getStrategyApi } from "@/api";
import { StrategyType } from "@/types";

export default () => {
  const [list, setList] = useState<Array<StrategyType>>([]);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [tabIndex, setTabIndex] = useState<string | number>(2);
  const pager = { page: "0", limit: "10" };

  function getData(time = menus[tabIndex].key, flag = false) {
    setLoading(true);
    pager.page = pager.page + 1;
    getStrategyApi({ ...pager, time }).then(
      (res: { rows: Array<StrategyType>; total: number }) => {
        let newList: Array<StrategyType> = [];
        if (flag) {
          newList.push(...res.rows);
        } else newList.push(...list, ...res.rows);
        setList(newList); // 使用 prevList 来追加数据
        setHasMore(newList.length < res.total); // 更新 hasMore
        setLoading(false);
      }
    );
  }
  const menus = [
    { title: "近一周", key: "week" },
    { title: "昨天", key: "yesterday" },
    { title: "今天", key: "today" },
    { title: "明天", key: "tomorrow" },
  ];
  function handleChange(e) {
    getData(menus[e].key, true);
    setTabIndex(e);
  }
  return (
    <View>
      <ConfigProvider
        theme={{
          tabFontSize: "16px",
          tabsNavBackgroundColor: "#F6F7FB",
        }}
      >
        <Tabs
          animated
          value={tabIndex}
          onChange={handleChange}
          swipeable
          sticky
        >
          {menus.map((menu) => {
            return (
              <Tabs.TabPane key={menu.key} title={menu.title}>
                <List loading={loading} hasMore={hasMore} onLoad={getData}>
                  <View className="flex flex-col gap-3 mt-2 px-4">
                    {list.map((item: StrategyType, i) => (
                      <MatchCard item={item} key={i} />
                    ))}
                  </View>
                  <List.Placeholder>
                    <View className="text-xs">
                      {loading && <Loading size="24px">加载中...</Loading>}
                      {!hasMore && "没有更多了"}
                    </View>
                  </List.Placeholder>
                </List>
              </Tabs.TabPane>
            );
          })}
        </Tabs>
      </ConfigProvider>
    </View>
  );
};
